package org.gluedom.data;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Comparator;
import java.util.List;

import com.google.common.base.Function;

public class Property implements Immutable {
	private final String name;
	private final String value;

	private volatile int hash = 0;

	public String getName() {
		return name;
	}

	public String getValue() {
		return value;
	}

	private Property(String name, String value) {
		assert name != null;
		assert value != null;
		this.name = name;
		this.value = value;
	}

	public static Property of(String name, String value) {
		return new Property(checkNotNull(name), checkNotNull(value));
	}

	static String findProperty(String name, List<Property> properties) {
		return FunctionalHashedComparator.findListEntry(Property.of(name, ""),
				properties, Property.PROPERTYHASH_COMPARATOR).getValue();
	}

	static final Function<Property, String> PROPERTYNAME_FUNCTION = new Function<Property, String>() {
		@Override
		public String apply(Property property) {
			return property.getName();
		}
	};

	static final Comparator<Property> PROPERTYHASH_COMPARATOR = FunctionalHashedComparator
			.fromFunction(PROPERTYNAME_FUNCTION);

	@Override
	public String toString() {
		return name + " = " + value;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Property))
			return false;
		Property other = (Property) obj;
		if (hashCode() != other.hashCode())
			return false;
		if (!name.equals(other.name))
			return false;
		if (!value.equals(other.value))
			return false;
		return true;
	}

	@Override
	public int hashCode() {
		if (hash == 0) {
			int result = 59792;
			result = 31 * result + name.hashCode();
			result = 31 * result + value.hashCode();
			hash = result;
		}
		return hash;
	}
}
